/**
 * @File   : layout.tsx
 * @Author : xue.xiaoBing
 * @Date   : 2024/3/1 16:32
 * @Desc   : 二维码生成工具
 * */

import {QRCode} from 'taro-code';
import {View} from "@tarojs/components";
import {useCallback, useRef, useState} from "react";
import {Button, Form, Input, Notify} from '@nutui/nutui-react-taro';
import Taro, {authorize, env, getFileSystemManager, getSetting, saveImageToPhotosAlbum,} from "@tarojs/taro";

import './index.scss';

export default function Code() {
  // 二维码标签
  const ref = useRef<any>();
  // 二维码数据
  const [codeData, setCodeData] = useState<any>(null);
  // 消息通知
  const [notify, setNotify] = useState({
    message: '',
    type: 'danger',
    visible: false,
  })

  // form表单提交
  const submitSucceed = (values: any) => {
    // Taro.showToast({title: JSON.stringify(values), icon: 'success'})
    const wifiInfo = `WIFI:T:${values.type};S:${values.acount};P:${values.password};H:true;;`
  }

  // 保存二维码
  const handleSaveCode = useCallback(() => {
    getSetting({
      success: function ({authSetting}) {
        //没有权限则申请`
        if (!authSetting["scope.writePhotosAlbum"]) {
          authorize({
            scope: "scope.writePhotosAlbum",
            success: () => {
              //存储二维码
              handleWriteFile();
            },
          });
        } else handleWriteFile();
      },
    });
  }, []);


  const handleWriteFile = useCallback(() => {
    const {src} = ref.current.childNodes[0].props;
    const data = src.split(",")[1];
    const filePath = `${env.USER_DATA_PATH}/${Date.now()}.png`;
    const {writeFile} = getFileSystemManager();
    // 写入 获得文件路径
    writeFile({
      data,
      filePath,
      encoding: "base64",
      success: () => {
        //存入相册
        saveImageToPhotosAlbum({
          filePath,
          success: () => {
            console.log("👏");
            setNotify((state: any) => ({
              ...state,
              message: '已保存至相册',
              type: 'success',
              visible: true
            }))
          },
        });
      },
      fail: (err) => {
        console.error(err);
        setNotify((state: any) => ({
          ...state,
          message: err,
          type: 'danger',
          visible: true
        }))
      },
    });
  }, []);

  const scanCode = async () => {
    try {
      const res = await Taro.scanCode({
        onlyFromCamera: false, // 默认为true，表示只能从相机扫码，不允许从相册选择图片
        scanType: ['qrCode'], // 默认为["qrCode"]，如果需要扫描一维码则数组内填'barCode'
      })
      console.log(res)
    } catch (error) {
      console.error('扫码失败', error)
    }
  }


  return (
    <View className='code-page'>
      <Notify
        visible={notify.visible}
        type={notify.type}
        onClose={() => {
          setNotify((state: any) => ({
            ...state,
            visible: false
          }))
        }}
        onClick={() => {
          console.log('click')
        }}
      >
        {notify.message}
      </Notify>
      <div className='code-form'>
        <Form
          divider
          labelPosition='left'
          onFinish={(values) => submitSucceed(values)}
          footer={
            <div
              style={{
                display: 'flex',
                justifyContent: 'center',
                width: '100%',
              }}
            >
              <Button formType='submit' type='primary'>
                生成
              </Button>
              <Button formType='reset' style={{marginLeft: '20px'}}>
                重置
              </Button>
            </div>
          }
        >
          <Form.Item
            label='wifi账号'
            name='acount'
            rules={[{required: true, message: "请输入wifi账号"}]}
          >
            <Input placeholder='请输入wifi账号' type='text'/>
          </Form.Item>
          <Form.Item
            label='wifi密码'
            name='password'
            rules={[
              {required: true, message: "请输入wifi密码"},
            ]}
          >
            <Input placeholder='请输入wifi密码' type='text'/>
          </Form.Item>
          <Form.Item
            label='加密类型'
            name='type'
            rules={[{required: true, message: "请输入加密类型"}]}
          >
            <Input placeholder='类型:WEP/WPA/WPA2/WPA3' type='text'/>
          </Form.Item>
        </Form>
      </div>
      <div className='generation-code'>
        <div className='code-area'>
          <View ref={ref}>
            {
              codeData ?
                <QRCode
                  scale={1}
                  size={200}
                  typeNumber={2}
                  text={codeData}
                  // text='wifissid://WIFI:S:YourWifiName;T:WPA;P:YourWifiPassword;;'
                  errorCorrectLevel='M'
                /> :
                <div className='hint'>
                  填写信息生成二维码
                </div>
            }
          </View>
        </div>
        <div className='operation-area'>
          <Button type='success' disabled={!codeData} onClick={handleSaveCode}>
            保存二维码
          </Button>
          {/*<Button type='success' disabled={!codeData} onClick={scanCode}>*/}
          {/*  扫一扫*/}
          {/*</Button>*/}
        </div>
      </div>
    </View>
  )
}
